#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速功能验证脚本 - 验证A股智能预测分析系统核心功能
"""

import logging
from datetime import datetime

# 设置日志级别
logging.basicConfig(level=logging.WARNING)

def quick_test():
    """快速功能测试"""
    print("🚀 A股智能预测分析系统 - 快速功能验证")
    print(f"验证时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}")
    print("="*50)
    
    results = {}
    
    # 1. 数据获取测试
    print("\n📊 1. 数据获取功能测试")
    try:
        from data_fetcher import StockDataFetcher
        fetcher = StockDataFetcher()
        
        # 测试获取股票数据
        data = fetcher.get_stock_data("000001", period="1mo")
        if data is not None and not data.empty:
            price = data['close'].iloc[-1]
            print(f"   ✅ 平安银行数据获取成功 - 最新价格: ¥{price:.2f}")
            results['数据获取'] = True
        else:
            print("   ❌ 数据获取失败")
            results['数据获取'] = False
            
    except Exception as e:
        print(f"   ❌ 数据获取异常: {e}")
        results['数据获取'] = False
    
    # 2. 技术分析测试
    print("\n📈 2. 技术分析功能测试")
    try:
        from advanced_technical_analysis import AdvancedTechnicalAnalysis
        analyzer = AdvancedTechnicalAnalysis()
        
        if results.get('数据获取', False):
            analysis = analyzer.comprehensive_analysis(data)
            if analysis:
                signal = analysis.get('buy_sell_system', {}).get('current_signal', '未知')
                print(f"   ✅ 技术分析成功 - 买卖信号: {signal}")
                results['技术分析'] = True
            else:
                print("   ❌ 技术分析计算失败")
                results['技术分析'] = False
        else:
            print("   ⚠️ 跳过技术分析（依赖数据获取）")
            results['技术分析'] = False
            
    except Exception as e:
        print(f"   ❌ 技术分析异常: {e}")
        results['技术分析'] = False
    
    # 3. 预测模型测试
    print("\n🔮 3. 预测模型功能测试")
    try:
        from prediction_model import StockPredictor
        predictor = StockPredictor()
        
        if results.get('数据获取', False):
            # 获取更多数据用于预测
            pred_data = fetcher.get_stock_data("000001", period="6mo")
            if pred_data is not None and len(pred_data) >= 60:
                prediction = predictor.predict_stock_trend(pred_data, "000001")
                if prediction and prediction.get('trend') != '未知':
                    trend = prediction.get('trend', '未知')
                    confidence = prediction.get('confidence', 0)
                    print(f"   ✅ 预测成功 - 趋势: {trend}, 置信度: {confidence:.1%}")
                    results['预测模型'] = True
                else:
                    print("   ❌ 预测模型计算失败")
                    results['预测模型'] = False
            else:
                print("   ⚠️ 预测数据不足")
                results['预测模型'] = False
        else:
            print("   ⚠️ 跳过预测测试（依赖数据获取）")
            results['预测模型'] = False
            
    except Exception as e:
        print(f"   ❌ 预测模型异常: {e}")
        results['预测模型'] = False
    
    # 4. 分红信息测试
    print("\n🎁 4. 分红信息功能测试")
    try:
        if results.get('数据获取', False):
            dividend_info = fetcher.get_dividend_info("000001")
            if dividend_info is not None and not dividend_info.empty:
                print(f"   ✅ 分红信息获取成功 - {len(dividend_info)}条记录")
                results['分红信息'] = True
            else:
                print("   ⚠️ 暂无分红记录")
                results['分红信息'] = True  # 没有分红也算正常
        else:
            print("   ⚠️ 跳过分红测试（依赖数据获取）")
            results['分红信息'] = False
            
    except Exception as e:
        print(f"   ❌ 分红信息异常: {e}")
        results['分红信息'] = False
    
    # 5. Web应用连接测试
    print("\n🌐 5. Web应用连接测试")
    try:
        import requests
        response = requests.get('http://localhost:8501', timeout=5)
        if response.status_code == 200:
            print("   ✅ Web应用连接正常")
            results['Web应用'] = True
        else:
            print(f"   ❌ Web应用响应异常: {response.status_code}")
            results['Web应用'] = False
    except Exception as e:
        print(f"   ❌ Web应用连接失败: {e}")
        results['Web应用'] = False
    
    # 汇总结果
    print("\n" + "="*50)
    print("📊 功能验证结果汇总:")
    
    passed = sum(1 for v in results.values() if v)
    total = len(results)
    
    for name, status in results.items():
        icon = "✅" if status else "❌"
        print(f"   {icon} {name}")
    
    success_rate = passed / total if total > 0 else 0
    
    print(f"\n📈 通过率: {passed}/{total} ({success_rate:.1%})")
    
    if success_rate >= 0.8:
        print("🎊 总体状态: 优秀 - 系统运行正常!")
        print("💡 建议: 可以正常使用系统")
        print("🌐 访问地址: http://localhost:8501")
        return True
    elif success_rate >= 0.6:
        print("⚠️ 总体状态: 良好 - 系统基本可用")
        print("💡 建议: 部分功能可能需要优化")
        return True
    else:
        print("❌ 总体状态: 需要修复")
        print("💡 建议: 请检查失败的功能模块")
        return False

if __name__ == "__main__":
    try:
        success = quick_test()
        exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n⚠️ 测试被中断")
        exit(1)
    except Exception as e:
        print(f"\n❌ 测试异常: {e}")
        exit(1)
